package com.example.webmodule.strategy;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.example.webmodule.entity.ApiPathVo;
import com.example.webmodule.entity.ServiceInfo;
import com.example.webmodule.util.OpenApiProcessor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.List;

/**
 * 抽象Web注册中心策略
 */
@Slf4j
public abstract class AbstractWebRegistryStrategy implements RegistrySelectStrategy {

    private final OkHttpClient okHttpClient;

    private final String urlTemplate = "http://{}:{}/v3/api-docs";

    public AbstractWebRegistryStrategy(OkHttpClient okHttpClient) {
        this.okHttpClient = okHttpClient;
    }

    @Override
    public List<ApiPathVo> fetchApiPaths(ServiceInfo serviceInfo) {
        // http://服务地址:端口号/v3/api-docs
        String url = StrUtil.format(urlTemplate, serviceInfo.getIp(), serviceInfo.getPort());
        log.info("fetchApiPaths start url={}", url);
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                String responseBody = response.body().string();
                log.info("{}, responseBody:{}", serviceInfo.getServiceId(), responseBody);
                List<ApiPathVo> openApiList = OpenApiProcessor.processOpenApi(responseBody);
                log.info("{}, openApiList:{}", serviceInfo.getServiceId(), JSON.toJSONString(openApiList));
                log.info("fetchApiPaths end");
                return openApiList;
            }
        } catch (IOException e) {
            log.info("api request error", e);
        }
        log.info("{}, fetchApiPaths end return is empty", serviceInfo.getServiceId());
        return Lists.newArrayList();
    }
}
